package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.util.Collector;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/25 10:36
 */
public class Flink04_Function_TableAgg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        Table table = tenv.fromDataStream(waterSensorStream);
        
        table
            .groupBy($("id"))
            .flatAggregate(call(Top2.class, $("vc")).as("top"))
            .select($("id"), $("top"))
            .execute()
            .print();
        
        // sql中使用 制表聚合函数:    目前还不支持
        
    }
    
    public static class FirstSecond {
        public Integer first = 0;
        public Integer second = 0;
    }
    
    public static class Top2 extends TableAggregateFunction<String, FirstSecond> {
        
        //初始化累加器
        @Override
        public FirstSecond createAccumulator() {
            return new FirstSecond();
        }
        
        // 对只进行聚合
        public void accumulate(FirstSecond acc, Integer vc) {
            if (vc > acc.first) {
                acc.second = acc.first;
                acc.first = vc;
            } else if (vc > acc.second) {
                acc.second = vc;
            }
        }
        
        // 向表中放入结果:  out.collect 方法, 调用一次, 就会有一行
        public void emitValue(FirstSecond acc, Collector<String> out) {
            out.collect("最大水位: " + acc.first);
            
            if (acc.second > 0) {
                
                out.collect("二大水位: " + acc.second);
            }
        }
        
    }
    
}
/*
sensor_1   20
    
    sensor_1   20
    
sensor_1   30
    sensor_1   30
    sensor_1   20
    


 */

